import express from 'express';
import { User } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt } from '../../utils/utils'; // 工具类
import { verifySession } from '../../common/verify'; // 验证码集合

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // User.Modal.sync();
  // 权限校验
  // await checkPermission(Request, Response, minLevel)

  let param = Request.body

  let mobileSession = verifySession[param.mobile]
  if(param.mobile === '13040702395' && param.verify === '888888'){ // 测试账号
    await getUserIdByMobile(param.mobile).then(res => {
      // 构造token并存储
      let tokenOrigin = `{"uid":"24","timeStamp":"${new Date().valueOf()}"}`
      Response.append('token', aesEncrypt(tokenOrigin));
    });
    Response.json({
      data: '登陆成功'
    })
  }else if(param.mobile === '13888888888' && param.verify === '888888'){ // 测试账号
    await getUserIdByMobile(param.mobile).then(res => {
      // 构造token并存储
      let tokenOrigin = `{"uid":"1","timeStamp":"${new Date().valueOf()}"}`
      Response.append('token', aesEncrypt(tokenOrigin));
    });
    Response.json({
      data: '登陆成功'
    })
  } else if (mobileSession && JSON.parse(mobileSession).expiredAt >= new Date().valueOf() && JSON.parse(mobileSession).verify === param.verify) {
    delete verifySession[param.mobile] // 清除验证码
    User.Modal.upsert({ mobile: param.mobile }).then(async res => {
      await getUserIdByMobile(param.mobile).then(res => {
        // 构造token并存储
        let tokenOrigin = `{"uid":"${res.id}","timeStamp":"${new Date().valueOf()}"}`
        Response.append('token', aesEncrypt(tokenOrigin));
      });
      // res为true则新增，false则更新
      let msg = '登陆成功'
      if (res === true) {
        msg = '一键注册成功'
      }
      Response.json({
        data: msg
      })
    }).catch(err => {
      console.log(err)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  } else {
    Response.status(300).send({ message: '当前验证码已过期或输入错误' });
  }
});

function getUserIdByMobile(mobile, Response) {
  // 通过openId获取用户id
  return new Promise((resolve, reject) => {
    User.Modal.findAll({
      where: {
        mobile: mobile,
      },
      raw: true,
    }).then(res => {
      if (res && res.length > 0) {
        resolve(res[0])
      } else {
        Response.status(300).send({ message: "查询用户失败，请提供正确手机号" });
      }
    }).catch(err => {
      console.log(err.name)
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

module.exports = router;